#include "slTexture.hh"


slTexture::slTexture(std::string fileName)
{
	_fileName = fileName;
}

slTexture::slTexture()
{
    _fileName = "";
}

slTexture::~slTexture()
{

}

bool slTexture::load()
{
    if (_fileName == "")
    {
        std::cerr << "Error : Texture not allocated" << std::endl;
        return false;
    }

	SDL_Surface *imageSDL = IMG_Load(_fileName.c_str());

	if (!imageSDL)
	{
		std::cerr << SDL_GetError() << std::endl;
		return false;
	}

    glGenTextures(1, &_id);
    glBindTexture(GL_TEXTURE_2D, _id);

    GLenum formatInterne = 0;
    GLenum format = 0;

    if(imageSDL->format->BytesPerPixel == 3)
    {
        formatInterne = GL_RGB;

        if(imageSDL->format->Rmask == 0xff)
            format = GL_RGB;
        else
            format = GL_BGR;
    }
    else if(imageSDL->format->BytesPerPixel == 4)
    {    
        formatInterne = GL_RGBA;

        if(imageSDL->format->Rmask == 0xff)
            format = GL_RGBA;
        else
            format = GL_BGRA;
    }
    else
    {
        std::cout << "Erreur, format interne de l'image inconnu" << std::endl;
        SDL_FreeSurface(imageSDL);

        return false;
    }

    glTexImage2D(GL_TEXTURE_2D, 0, formatInterne, imageSDL->w, imageSDL->h, 0, format, GL_UNSIGNED_BYTE, imageSDL->pixels);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glBindTexture(GL_TEXTURE_2D, 0);
    SDL_FreeSurface(imageSDL);

    return true;
}

bool slTexture::loadTexture(const std::string &fileName)
{
    SDL_Surface *imageSDL = IMG_Load(fileName.c_str());

    if (!imageSDL)
    {
        std::cerr << SDL_GetError() << std::endl;
        return false;
    }

    glGenTextures(1, &_id);
    glBindTexture(GL_TEXTURE_2D, _id);

    GLenum formatInterne = 0;
    GLenum format = 0;

    if(imageSDL->format->BytesPerPixel == 3)
    {
        formatInterne = GL_RGB;

        if(imageSDL->format->Rmask == 0xff)
            format = GL_RGB;
        else
            format = GL_BGR;
    }
    else if(imageSDL->format->BytesPerPixel == 4)
    {    
        formatInterne = GL_RGBA;

        if(imageSDL->format->Rmask == 0xff)
            format = GL_RGBA;
        else
            format = GL_BGRA;
    }
    else
    {
        std::cout << "Erreur, format interne de l'image inconnu" << std::endl;
        SDL_FreeSurface(imageSDL);

        return false;
    }

    glTexImage2D(GL_TEXTURE_2D, 0, formatInterne, imageSDL->w, imageSDL->h, 0, format, GL_UNSIGNED_BYTE, imageSDL->pixels);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glBindTexture(GL_TEXTURE_2D, 0);
    SDL_FreeSurface(imageSDL);

    return true;
}

GLuint slTexture::getID() const
{
	return _id;
}
